import { useUserStore } from '@/stores/user'

// Token相关操作
export const TOKEN_KEY = 'admin_token'
export const REFRESH_TOKEN_KEY = 'admin_refresh_token'

// 获取Token
export const getToken = () => {
  return localStorage.getItem(TOKEN_KEY)
}

// 设置Token
export const setToken = (token) => {
  localStorage.setItem(TOKEN_KEY, token)
}

// 移除Token
export const removeToken = () => {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(REFRESH_TOKEN_KEY)
}

// 获取刷新Token
export const getRefreshToken = () => {
  return localStorage.getItem(REFRESH_TOKEN_KEY)
}

// 设置刷新Token
export const setRefreshToken = (token) => {
  localStorage.setItem(REFRESH_TOKEN_KEY, token)
}

// 检查是否已登录
export const isAuthenticated = () => {
  return !!getToken()
}

// 检查Token是否过期
export const isTokenExpired = (token) => {
  if (!token) return true
  
  try {
    const payload = JSON.parse(atob(token.split('.')[1]))
    return payload.exp * 1000 < Date.now()
  } catch {
    return true
  }
}

// 解析Token
export const parseToken = (token) => {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]))
    return payload
  } catch {
    return null
  }
}

// 检查权限
export const hasPermission = (permission) => {
  const userStore = useUserStore()
  return userStore.permissions.includes(permission)
}

// 检查角色
export const hasRole = (role) => {
  const userStore = useUserStore()
  return userStore.roles.includes(role)
}

// 检查多个权限（AND操作）
export const hasAllPermissions = (permissions) => {
  const userStore = useUserStore()
  return permissions.every(permission => 
    userStore.permissions.includes(permission)
  )
}

// 检查多个权限（OR操作）
export const hasAnyPermission = (permissions) => {
  const userStore = useUserStore()
  return permissions.some(permission => 
    userStore.permissions.includes(permission)
  )
}

// 检查多个角色（AND操作）
export const hasAllRoles = (roles) => {
  const userStore = useUserStore()
  return roles.every(role => userStore.roles.includes(role))
}

// 检查多个角色（OR操作）
export const hasAnyRole = (roles) => {
  const userStore = useUserStore()
  return roles.some(role => userStore.roles.includes(role))
}

// 权限检查装饰器
export const requireAuth = (permission) => {
  return (target, propertyKey, descriptor) => {
    const originalMethod = descriptor.value
    descriptor.value = function (...args) {
      if (!hasPermission(permission)) {
        throw new Error('没有访问权限')
      }
      return originalMethod.apply(this, args)
    }
    return descriptor
  }
}

// 角色检查装饰器
export const requireRole = (role) => {
  return (target, propertyKey, descriptor) => {
    const originalMethod = descriptor.value
    descriptor.value = function (...args) {
      if (!hasRole(role)) {
        throw new Error('没有访问权限')
      }
      return originalMethod.apply(this, args)
    }
    return descriptor
  }
}

// 登出处理
export const logout = () => {
  const userStore = useUserStore()
  userStore.logout()
  removeToken()
  // 可以在这里添加其他登出逻辑
}

// 自动刷新Token
export const refreshTokenIfNeeded = async () => {
  const token = getToken()
  const refreshToken = getRefreshToken()
  
  if (!token || !refreshToken) {
    return false
  }
  
  // 如果Token即将过期（提前5分钟刷新）
  if (isTokenExpired(token) || willExpireSoon(token, 5 * 60 * 1000)) {
    try {
      const { refreshToken: authRefreshToken } = await import('@/api/auth')
      const response = await authRefreshToken(refreshToken)
      
      if (response.success) {
        setToken(response.data.token)
        setRefreshToken(response.data.refreshToken)
        return true
      }
    } catch (error) {
      console.error('Token refresh failed:', error)
      logout()
      return false
    }
  }
  
  return true
}

// 检查Token是否即将过期
const willExpireSoon = (token, threshold = 5 * 60 * 1000) => {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]))
    return payload.exp * 1000 - Date.now() < threshold
  } catch {
    return true
  }
}
